package com.wzj.yygh.user.controller.api;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.google.gson.Gson;
import com.wzj.yygh.common.exception.YyghException;
import com.wzj.yygh.common.result.R;
import com.wzj.yygh.common.result.ResultCode;
import com.wzj.yygh.common.utils.JwtHelper;
import com.wzj.yygh.model.user.UserInfo;
import com.wzj.yygh.user.service.UserInfoService;
import com.wzj.yygh.user.utils.ConstantProperties;
import com.wzj.yygh.user.utils.HttpClientUtils;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Api(tags = "微信扫码登录")
@Controller
@RequestMapping("api/")
@Slf4j
public class ApiWxController {
    @Autowired
    private ConstantProperties constantProperties;
    @Autowired
    private UserInfoService userInfoService;

    //微信登录方式一  在新页面中展示登录二维码
    @GetMapping("user/wx/getQRCodeUrl")
    public String getQRCodeUrl(HttpSession session) {
        try {
            String state = UUID.randomUUID().toString();//.replaceAll("-","");
            log.info("存储state,session_id => "+ session.getId());
            session.setAttribute("wx_open_state",state);
            String redirectUri = URLEncoder.encode(constantProperties.getRedirectUrl(),"UTF-8");

            String url = "https://open.weixin.qq.com/connect/qrconnect?" +
                    "appid=" + constantProperties.getAppId() +
                    "&redirect_uri=" + redirectUri +
                    "&response_type=code" + //授权临时票据
                    "&scope=snsapi_login" + //授权范围
                    "&state=" + state + //防止跨站请求伪造攻击
                    "#wechat_redirect"; //客户端跳转形式的回调
            return "redirect:" + url;
        } catch (Exception e) {
            throw new YyghException(ResultCode.ERROR,"生成二维码失败",e);
        }
    }

    //方式二 在内嵌网页中显示登录二维码
    @GetMapping("user/wx/getQRCodeParams")
    @ResponseBody
    public R getQRCodeParams(HttpSession session) {
        try {
            String state = UUID.randomUUID().toString();//.replaceAll("-","");
            log.info("存储state,session_id => "+ session.getId());
            session.setAttribute("wx_open_state",state);
            String redirectUri = URLEncoder.encode(constantProperties.getRedirectUrl(),"UTF-8");

            HashMap<String, Object> map = new HashMap<>();
            map.put("scope","snsapi_login");
            map.put("appid",constantProperties.getAppId());
            map.put("redirectUri", redirectUri);
            map.put("state",state);
            return R.ok().data(map);
        } catch (UnsupportedEncodingException e) {
            throw new YyghException(ResultCode.ERROR,"生成二维码失败",e);
        }
    }

    @GetMapping("ucenter/wx/callback")
    public String callback(String code,String state,HttpSession session) {

        try {
            log.info("callback被调用");
            log.info("获取state,session_id => "+ session.getId());
            log.info("参数中code = {}, 参数中state = {}",code,state);
            String sessionState =(String) session.getAttribute("wx_open_state");
            log.info("session中state = {}",sessionState);

            if (!state.equals(sessionState)){
                log.error("state参数不一致");
            }

            if (StringUtils.isEmpty(code) || StringUtils.isEmpty(state) ) {
                throw new YyghException("非法回调",20015);
            }

            String accessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                    "?appid=" + constantProperties.getAppId() +
                    "&secret=" + constantProperties.getAppSecret() +
                    "&code=" + code +
                    "&grant_type=authorization_code";
            String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
            Gson gson = new Gson();
            Map accessTokenInfoResultMap = gson.fromJson(accessTokenInfo, Map.class);

            if (accessTokenInfoResultMap.get("errcode") != null) {
                System.out.println(accessTokenInfoResultMap.get("errcode"));
                throw new YyghException("获取accessToken失败",ResultCode.ERROR);
            }

            //根据openid和accessToken获取用户信息
            String accessToken = (String) accessTokenInfoResultMap.get("access_token");
            String openid = (String) accessTokenInfoResultMap.get("openid");
            //根据openID获取是否存在用户
            UserInfo userInfo = userInfoService.selectUserInfoByOpenId(openid);
            if (userInfo == null) {
                log.info("注册用户......");
                //调用微信接口，根据accessToken获取资源服务器上的资源
                String userInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=" + accessToken +
                        "&openid=" + openid;
                String userInfoString = HttpClientUtils.get(userInfoUrl);
                gson = new Gson();
                Map userInfoStringResultMap = gson.fromJson(userInfoString, Map.class);
                //获取用户信息
                String nickName = (String) userInfoStringResultMap.get("nickName");

                //获取用户头像网络地址
                String headimgurl = (String) userInfoStringResultMap.get("headimgurl");
                log.warn("headimgurl ===> " +headimgurl );

                if ( accessTokenInfoResultMap.get("errcode") != null) {
                    throw new YyghException("获取accessToken失败",ResultCode.ERROR);
                }
                userInfo = new UserInfo();
                userInfo.setNickName(nickName);
                userInfo.setOpenid(openid);
                userInfo.setStatus(1);
                userInfoService.save(userInfo);
            }else {
                //如果异常
                if (userInfo.getStatus() == 0) {
                    throw new YyghException("用户已禁用",ResultCode.ERROR);
                }
            }
            //登录 生成jwt
            String token = JwtHelper.createToken(userInfo.getId(), userInfo.getName());
            //方案一 操作token

            //方案二 通过URL传递
            return "redirect:http://localhost:3000/?token =" +token +
                    "&name=" + URLEncoder.encode(userInfo.getName(),"utf-8") +
                    "&openid=" + openid + "&phone" + userInfo.getPhone();
        } catch (Exception e) {
            throw new YyghException(ResultCode.ERROR,"登录失败",e);
        }
    }
}
